<template>
  <div class="register-container">
    <div class="platform-info">
      <h1>工业电商平台</h1>
      <p class="subtitle">专业机械工业品采购平台</p>
    </div>

    <div class="register-box">
      <h2><i class="icon fas fa-user-plus"></i> 用户注册</h2>
      <p class="register-tip">请填写以下信息创建您的账户</p>

      <form @submit.prevent="handleRegister" class="register-form">
        <div class="form-row">
          <div class="form-group">
            <label for="username">用户名 <span class="required">*</span></label>
            <input
                id="username"
                v-model.trim="user.username"
                type="text"
                placeholder="4-20个字符，支持字母、数字和下划线"
                required
            />
            <p v-if="errors.username" class="error-text">{{ errors.username }}</p>
          </div>

          <div class="form-group">
            <label for="phone">手机号 <span class="required">*</span></label>
            <input
                id="phone"
                v-model.trim="user.phone"
                type="tel"
                placeholder="11位有效手机号码"
                required
            />
            <p v-if="errors.phone" class="error-text">{{ errors.phone }}</p>
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="password">密码 <span class="required">*</span></label>
            <input
                id="password"
                v-model="user.password"
                type="password"
                placeholder="至少8位，包含字母和数字"
                required
            />
            <p v-if="errors.password" class="error-text">{{ errors.password }}</p>
          </div>

          <div class="form-group">
            <label for="confirmPassword">确认密码 <span class="required">*</span></label>
            <input
                id="confirmPassword"
                v-model="confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                required
            />
            <p v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</p>
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="email">电子邮箱 <span class="required">*</span></label>
            <input
                id="email"
                v-model.trim="user.email"
                type="email"
                placeholder="您的常用电子邮箱"
                required
            />
            <p v-if="errors.email" class="error-text">{{ errors.email }}</p>
          </div>

          <div class="form-group">
            <label for="realName">真实姓名</label>
            <input
                id="realName"
                v-model.trim="user.real_name"
                type="text"
                placeholder="您的真实姓名（选填）"
            />
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label>性别</label>
            <div class="gender-group">
              <label class="gender-option">
                <input type="radio" v-model="user.gender" :value="0" />
                <span>保密</span>
              </label>
              <label class="gender-option">
                <input type="radio" v-model="user.gender" :value="1" />
                <span>男</span>
              </label>
              <label class="gender-option">
                <input type="radio" v-model="user.gender" :value="2" />
                <span>女</span>
              </label>
            </div>
          </div>

          <div class="form-group">
            <label for="age">年龄</label>
            <input
                id="age"
                v-model.number="user.age"
                type="number"
                min="18"
                max="100"
                placeholder="您的年龄（选填）"
            />
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="question">安全问题</label>
            <select id="question" v-model="user.question">
              <option value="">请选择安全问题</option>
              <option value="您母亲的姓名？">您母亲的姓名？</option>
              <option value="您出生的城市是？">您出生的城市是？</option>
              <option value="您第一个宠物的名字？">您第一个宠物的名字？</option>
              <option value="您的小学校名？">您的小学校名？</option>
              <option value="自定义问题">自定义问题</option>
            </select>
          </div>

          <div class="form-group" v-if="user.question === '自定义问题'">
            <label for="customQuestion">自定义问题</label>
            <input
                id="customQuestion"
                v-model.trim="user.question"
                type="text"
                placeholder="请设置您的安全问题"
            />
          </div>

          <div v-else class="form-group">
            <label for="answer">安全问题答案</label>
            <input
                id="answer"
                v-model.trim="user.answer"
                type="text"
                placeholder="您的安全问题答案"
            />
          </div>
        </div>

        <div class="form-actions">
          <button type="submit" :disabled="isSubmitting" class="register-button">
            {{ isSubmitting ? '注册中...' : '立即注册' }}
            <i class="fas fa-arrow-right"></i>
          </button>
        </div>

        <div class="login-link">
          已有账号？<router-link to="/login">立即登录</router-link>
        </div>

        <div v-if="submitError" class="error-message">
          <i class="error-icon">!</i> {{ submitError }}
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import request from '../../utils/request';

// 响应式数据
const user = reactive({
  username: '',
  password: '',
  phone: '',
  email: '',
  real_name: '',
  gender: 0,
  age: null,
  question: '',
  answer: '',
  status: 1,
  is_admin: 0
});

const confirmPassword = ref('');
const isSubmitting = ref(false);
const submitError = ref('');
const errors = reactive({
  username: '',
  phone: '',
  password: '',
  confirmPassword: '',
  email: ''
});

// 获取router
const router = useRouter();

const validateForm = () => {
  let isValid = true;

  // 重置错误消息
  errors.username = '';
  errors.phone = '';
  errors.password = '';
  errors.confirmPassword = '';
  errors.email = '';

  // 用户名验证
  if (!user.username) {
    errors.username = '请输入用户名';
    isValid = false;
  } else if (!/^[a-zA-Z0-9_]{4,20}$/.test(user.username)) {
    errors.username = '用户名必须为4-20个字符，仅支持字母、数字和下划线';
    isValid = false;
  }

  // 手机号验证
  if (!user.phone) {
    errors.phone = '请输入手机号';
    isValid = false;
  } else if (!/^1[3-9]\d{9}$/.test(user.phone)) {
    errors.phone = '请输入有效的手机号码';
    isValid = false;
  }

  // 密码验证
  if (!user.password) {
    errors.password = '请输入密码';
    isValid = false;
  } else if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(user.password)) {
    errors.password = '密码至少8位，必须包含字母和数字';
    isValid = false;
  }

  // 确认密码验证
  if (!confirmPassword.value) {
    errors.confirmPassword = '请确认密码';
    isValid = false;
  } else if (confirmPassword.value !== user.password) {
    errors.confirmPassword = '两次输入的密码不一致';
    isValid = false;
  }

  // 邮箱验证
  if (!user.email) {
    errors.email = '请输入电子邮箱';
    isValid = false;
  } else if (!/^\w+([-]?\w+)*@\w+([-]?\w+)*(\.\w{2,3})+$/.test(user.email)) {
    errors.email = '请输入有效的电子邮箱地址';
    isValid = false;
  }

  return isValid;
};

const handleRegister = async () => {
  // 表单验证
  if (!validateForm()) return;

  isSubmitting.value = true;
  submitError.value = '';

  try {
    // 修改为发送JSON格式数据
    const response = await request.post('/user/register', user, {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    if (response.data.status === 200) {
      router.push('/login?from=register');
    } else {
      submitError.value = response.data.msg || '注册失败，请稍后重试';
    }
  } catch (error) {
    console.error('注册错误:', error);
    if (error.response) {
      const status = error.response.status;
      if (status === 400) {
        submitError.value = error.response.data.msg || '注册信息格式错误';
      } else if (status === 409) {
        submitError.value = '用户名、手机号或邮箱已被注册';
      } else {
        submitError.value = `服务器错误 (${status})`;
      }
    } else {
      submitError.value = '网络连接错误，请稍后重试';
    }
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
.register-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.platform-info {
  text-align: center;
  margin-bottom: 3rem;
}

.platform-info h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 0.5rem;
}

.subtitle {
  font-size: 1.2rem;
  color: #666;
}

.register-box {
  width: 100%;
  max-width: 450px;
  padding: 2.5rem;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.register-box h2 {
  text-align: center;
  font-size: 1.8rem;
  color: #333;
  margin-bottom: 1rem;
}

.register-tip {
  text-align: center;
  color: #666;
  margin-bottom: 2rem;
}

.register-form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.form-row {
  display: flex;
  gap: 1.5rem;
}

.form-row > div {
  flex: 1;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

label {
  font-weight: 500;
  color: #333;
  font-size: 0.95rem;
}

input, select {
  padding: 0.75rem 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.3s;
}

input:focus, select:focus {
  border-color: #1890ff;
  outline: none;
}

.error-text {
  color: #e74c3c;
  font-size: 0.85rem;
  margin-top: 0.4rem;
  height: 1.2rem;
}

.gender-group {
  display: flex;
  gap: 1.5rem;
  padding-top: 0.5rem;
}

.gender-option {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  font-size: 1rem;
}

.form-actions {
  margin-top: 1.5rem;
  text-align: center;
}

.register-button {
  padding: 0.75rem;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 500;
  transition: background-color 0.3s;
}

.register-button:hover {
  background-color: #40a9ff;
}

.register-button:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
}

.login-link {
  text-align: center;
  font-size: 0.9rem;
  color: #666;
  margin-top: 1rem;
}

.login-link a {
  color: #1890ff;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}

.error-message {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #f5222d;
  margin: 0;
  padding: 0.75rem;
  background-color: #fff1f0;
  border-radius: 4px;
  font-size: 0.9rem;
}

.error-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 1.2rem;
  height: 1.2rem;
  background-color: #f5222d;
  color: white;
  border-radius: 50%;
  font-style: normal;
  font-weight: bold;
  font-size: 0.8rem;
}

.icon {
  font-size: 1.3em;
}

@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 1rem;
  }

  .register-box {
    padding: 1.5rem;
  }

  .platform-info h1 {
    font-size: 2rem;
  }
}
</style>